package com.example.config.security;

import com.example.config.security.filter.CheckTokenFilter;
import com.example.config.security.handler.AnonymousAuthenticationHandler;
import com.example.config.security.handler.CustomerAccessDeniedHandler;
import com.example.config.security.handler.LoginFailureHandler;
import com.example.config.security.handler.LoginSuccessHandler;
import com.example.config.security.service.CustomerUserDetailsService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

@Configuration
@EnableWebSecurity
//开启权限注解控制
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private CustomerUserDetailsService customerUserDetailsService;
    @Resource
    private LoginSuccessHandler loginSuccessHandler;
    @Resource
    private LoginFailureHandler loginFailureHandler;
    @Resource
    private AnonymousAuthenticationHandler anonymousAuthenticationHandler;
    @Resource
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;
    @Resource
    private CheckTokenFilter checkTokenFilter;

    /**
     * 密码加密
     * @return
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //登录前进行过滤    表单登录
        http.addFilterBefore(checkTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.formLogin()
                //自定义登录请求url地址
                .loginProcessingUrl("/api/user/login")
                //设置登录验证成功或失败后的跳转地址
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
                //禁用csrf防御机制
                .and()
                .csrf().disable()
                //不创建session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                //设置需要被拦截的请求
                .and().authorizeRequests()
                //设置放行路径（不拦截登录请求）
                .antMatchers("/api/user/login").permitAll()
                .antMatchers("/files/**").permitAll()// 放行静态资源
                //设置其他请求都需要被拦截进行认证
                .anyRequest().authenticated()
                .and().exceptionHandling().authenticationEntryPoint(anonymousAuthenticationHandler)
                .accessDeniedHandler(customerAccessDeniedHandler)
                .and().cors();//允许跨域
    }

    /**
     * 配置认证处理器
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customerUserDetailsService)
                .passwordEncoder(passwordEncoder());
    }
}
